#
# import redis
#
# from constants import MysqlConstant
#
#
import redis

from constants import MysqlConstant, ColumnConstant


class RedisUtil:

    _instance = None
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls, *args, **kwargs)
        return cls._instance
    def __init__(self):
        config = MysqlConstant.REDIS_CONFIG
        self.host = config.get("host")
        self.port = config.get("port")
        self.password = config.get("password")
        self.db = 0
        self.timeout = None
        self.pool_size = 10
        self.r = redis.Redis(host=self.host, port=self.port, db=self.db,
                             password=self.password, socket_timeout=self.timeout)
        # self.r = self.connect()

    """
     链接redis库
    """
    def connect(self):
            return redis.Redis(host=self.host, port=self.port, db=self.db,
                               password=self.password, socket_timeout=self.timeout)

    def disconnect(self, r):
        r.close()

    def bytes2Str(self,bytes):
        if bytes is None:
            return ""
        if len(bytes)==0:
            return ""
        return bytes.decode('utf-8').strip('"')


    def hget(self,k1,k2):
        if not self.r.hexists(k1,k2):
            print(f"{k1} {k2} 不存在")
            return None
        return self.bytes2Str(self.r.hget(k1,k2))

    def hset(self,k1,k2,v):
        return self.r.hset(k1,k2,v)

    def hdel(self,k1,k2):
        return self.r.hdel(k1,k2)

    """
      获取key下的所有的值, 不过是一个二进制的值
    """
    def hgetall(self,k1):
        return self.r.hgetall(k1)

    def getTTL(self,key):
        return self.r.ttl(key)

    def getHistoryLotteryInfo(self):
        result = []
        try:
            data= self.r.lrange("modelData",0,-1)

            for item in data:
                result.append(self.bytes2Str(item))
        except:
            pass
        finally:
            return result

    def setHistoryLotteryInfo(self,str):
        # 读取所有的redis 缓存数据
        res = self.getHistoryLotteryInfo()
        if str not in res:
            self.r.lpush("modelData",str)


    def hasKey(self,key):
        return self.r.exists(key)
#     """
#         获取应用启动信息
#     """
#     # def getStartInfo(self,phone):
#     #     vo=UserVo()
#     #     # r = self.connect()
#     #     if self.r.exists(phone):
#     #         vo.setPhone(phone)
#     #         #  今天是否启动
#     #         vo.setTodayIsStart(self.bytes2Str(self.r.hget(phone, ColumnConstant.TODAY_IS_START)))
#     #         #  雪球模式轮数
#     #         vo.setSnowballCount(self.bytes2Str(self.r.hget(phone, ColumnConstant.SNOWBALL_MODEL_COUNT)))
#     #         #  每期雪球目标,小目标
#     #         vo.setSnowballtarget(self.bytes2Str(self.r.hget(phone, ColumnConstant.SNOWBALL_EVERY_WIN_SUM)))
#     #         #  爬虫启动时间(小时)
#     #         vo.setStartHour(self.bytes2Str(self.r.hget(phone, ColumnConstant.START_HOUR)))
#     #         #  爬虫停止时间(小时)
#     #         vo.setEndHour(self.bytes2Str(self.r.hget(phone, ColumnConstant.END_HOUR)))
#     #         # 今天盈利目标
#     #         vo.setWinAmount(self.bytes2Str(self.r.hget(phone, ColumnConstant.TODAY_WIN_SUM)))
#     #         # 今天止损目标
#     #         vo.setCostAmount(self.bytes2Str(self.r.hget(phone, ColumnConstant.TODAY_COST_SUM)))
#     #         # 是否交换卡片
#     #         vo.setExchangeIsCard(self.bytes2Str(self.r.hget(phone, ColumnConstant.EXCHANGE_IS_CARD)))
#     #         # 交换卡片次数
#     #         vo.setExchangeCardNum(self.bytes2Str(self.r.hget(phone, ColumnConstant.EXCHANGE_CARD_NUM)))
#     #         # 交换卡片频率,1d1次,3d1次,5d一次
#     #         vo.setExchangeCardFrequency(self.bytes2Str(self.r.hget(phone, ColumnConstant.EXCHANGE_CARD_FREQUENCY)))
#     #         # 模式
#     #         vo.setModel(self.bytes2Str(self.r.hget(phone, ColumnConstant.USER_MODE)))
#     #         # 用户通知列表
#     #         userType = self.bytes2Str(self.r.hget(phone, ColumnConstant.USER_TYPE))
#     #         vo.setIsScrpay(userType)
#     #         # 用户通知列表
#     #         vo.setUserNoticeList(self.bytes2Str(self.r.hget(phone, ColumnConstant.USER_NOTICE_LIST)))
#     #         # 当前雪球父节点索引,当前雪球子节点索引
#     #         if self.r.exists(phone) and self.r.hget(phone,ColumnConstant.CURRENT_SNOWBALL_PARENT_INDEX) is not None:
#     #             vo.setCurrentSnowballParentIndex(self.bytes2Str(self.r.hget(phone, ColumnConstant.CURRENT_SNOWBALL_PARENT_INDEX)))
#     #             vo.setCurrentSnowballChildrenIndex(self.bytes2Str(self.r.hget(phone, ColumnConstant.CURRENT_SNOWBALL_CHILDREN_INDEX)))
#     #         else:
#     #             vo.setCurrentSnowballParentIndex(0)
#     #             vo.setCurrentSnowballChildrenIndex(0)
#     #
#     #         vo.setEvertTarget(self.bytes2Str(self.r.hget(phone, ColumnConstant.EVERY_TARGET)))
#     #         return vo
#     #     else:
#     #         return vo
#     def bytes2Str(self, bytes):
#         if bytes is None:
#             return ""
#         if len(bytes)==0:
#             return ""
#         return bytes.decode('utf-8').strip('"')
#
#     def setStartText(self,startText,str=None):
#         r = self.connect()
#         r.set(startText,"true")
#         r.expire(startText,1*60*60*24)
#
#     def setUserToken(self,phone,userToken):
#         r = self.connect()
#         key = self.getUserTokenKey(phone)
#         if r.exists(phone):
#             r.set(key,userToken);
#             r.expire(key,1*60*60*12)
#
#     def setEveryTarget(self,phone,everyTarget):
#         r = self.connect()
#         r.hset(phone,ColumnConstant.EVERY_TARGET,everyTarget)
#
#
#     """
#         设置启动时间
#     """
#     def setStartHour(self,phone,startHour):
#         r = self.connect()
#         r.hset(phone,ColumnConstant.START_HOUR,startHour)
#
#     def getUserToken(self,phone):
#         r = self.connect()
#         key = self.getUserTokenKey(phone)
#         if r.exists(phone) and r.get(key) is not None:
#             return self.bytes2Str(self.r.get(key));
#         else:
#             return ""
#
#     def getUserTokenKey(self,phone):
#         return f"{phone}-{ColumnConstant.USER_TOKEN}"
#     def exists(self,str):
#         r = self.connect()
#         return r.exists(str)
#
#     def getTTL(self,phone):
#         key = self.getUserTokenKey(phone)
#         return self.r.ttl(key)
#     def setCurrentSnowballParentIndex(self,phone,currentSnowballParentIndex):
#         self.r.hset(phone,ColumnConstant.CURRENT_SNOWBALL_PARENT_INDEX,currentSnowballParentIndex)
#     def setCurrentSnowballChildrenIndex(self,phone,currentSnowballChildrenIndex):
#         self.r.hset(phone,ColumnConstant.CURRENT_SNOWBALL_CHILDREN_INDEX,currentSnowballChildrenIndex)
#
#     def getCurrentSnowballParentIndex(self,phone):
#         return self.bytes2Str(self.r.hget(phone,ColumnConstant.CURRENT_SNOWBALL_PARENT_INDEX))
#
#     def getCurrentSnowballChildrenIndex(self,phone):
#         return self.bytes2Str(self.r.hget(phone,ColumnConstant.CURRENT_SNOWBALL_CHILDREN_INDEX))
#
#     def getexchangeCardFlow(self,exchangeCardFlowKey):
#         if self.r.exists(exchangeCardFlowKey):
#             return True
#         return False
#     def setExchangeCardFlow(self,exchangeCardFlowKey):
#         self.r.set(exchangeCardFlowKey,"true")
#         self.r.expire(exchangeCardFlowKey,1*60*60*24)
if __name__ == '__main__':
    # 创建RedisUtils实例

    redis_utils1 = RedisUtil()
    print(f"是否存在这个值{not redis_utils1.hasKey('17120572203')}")
    # st1 = redis_utils1.hget("17120572208",ColumnConstant.USER_TOKEN)
    # print(st1)
    # # vo = redis_utils.hgetall("17120572208")
    # # print(vo)
    #
    # s = redis_utils1.hget("17120572204",ColumnConstant.START_HOUR)
    # print(s)
    # print(redis_utils.getTTL("17120572208")>10)
    # # r =redis_utils.connect()
    # # print(r.hget("18340057070",ColumnConstant.USER_TOKEN))
    # # 连接Redis
    # phone ="18303587942"
    # vo = redis_utils.getStartInfo(phone)
    # redis_utils.disconnect(r)